package cn.javadog.algorithm.m1_100;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 三数之和
 * https://leetcode-cn.com/problems/3sum/
 * @author Sprite
 */
public class Algorithm15 {
	public static void main(String[] args) {
	}


	public static List<List<Integer>> threeSum(int[] nums) {
		List<List<Integer>> res = new ArrayList<>();
		int len = nums.length;
		if(nums == null || len < 3) return res;
		Arrays.sort(nums);

		for (int i = 0; i < nums.length; i++) {
			if (nums[i] > 0) break;
			if (i > 0 && nums[i] == nums[i-1]) continue;

			int L = i + 1;
			int R = nums.length - 1;

			while (L < R){
				int sum = nums[L] + nums[R] + nums[i];

				if (sum == 0){
					res.add(Arrays.asList(nums[L],nums[R],nums[i]));
					while (L<R && nums[L] == nums[L+1]) L++;
					while (L<R && nums[R] == nums[R-1]) R--;
					L++;
					R--;
				}else if (sum < 0) L++;
				else if (sum > 0) R--;
			}

		}
		return res;
	}
}
